package com.yxj.checksystempicture.u;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.yxj.checksystempicture.i.TakePhotoResultListener;

public class CheckPictureUtil {

    public static final int PERMISSION_REQUEST_CODE = 100 ;
    public static final int PICK_MEDIA_REQUEST_CODE = 200 ;
    private Activity activity;
    public CheckPictureUtil(Activity activity){
        this.activity=activity;
    }

    /**
     * 检测权限
     * 然后开始
     */
    public  void open() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        } else {
            openMediaPicker();
        }
    }


    /**
     * 进入系统相册选择
     */
    private void openMediaPicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Files.getContentUri("external"));
        intent.setType("image/* video/*");
        String[] mimeTypes = {"image/*", "video/*"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        activity.startActivityForResult(intent, PICK_MEDIA_REQUEST_CODE);
    }


    /**
     * 选择图片结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_MEDIA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Uri selectedMediaUri = data.getData();
            if (selectedMediaUri != null) {
                if (takePhotoResultListener!=null){
                    takePhotoResultListener.onResult(UriUtils.uriToFile(activity,selectedMediaUri).getAbsolutePath());
                }
            }
        }
    }


    private TakePhotoResultListener takePhotoResultListener;
    public CheckPictureUtil setTakePhotoResultListener(TakePhotoResultListener takePhotoResultListener) {
        this.takePhotoResultListener = takePhotoResultListener;
        return this;
    }
}
